
#include <stdio.h>
#include <stdlib.h>
#include "sysv_msgque.h"

#include <boost/interprocess/ipc/message_queue.hpp>
using namespace boost::interprocess;
using namespace std;

int sysv_msg()
{
	SysVMsgSndQueue sndQue(0xFFFF0001, 8192);
	SysVMsgRcvQueue rcvQue(0xFFFF0001, 8192);
	
	int len, ret = 0;
	for( int i = 0; i < 10; i++ )
	{
		sprintf( (char*)sndQue.getMsgAddr(), 
			"Msg%03d.", i+1 );
		sndQue.setMsgLen(256);
		
		ret = sndQue.sendMsg();
		
		ret = rcvQue.recvMsg();
		
		len = rcvQue.getMsgLen();
		
		printf( "msg_len = %d, Msg: %s\n", len, (char*)rcvQue.getMsgAddr() );
		
	}
	
	for( ; ; )
	{
		ret = rcvQue.recvMsg();
		if ( ret == -1 )
			break;

		len = rcvQue.getMsgLen();
		
		printf( "msg_len = %d, Msg: %s\n", len, (char*)rcvQue.getMsgAddr() );

	}

	return 0;
}

int recv_msg()
{
   try{
      //Open a message queue.
      message_queue mq
         (open_or_create        	//open_or_create
         ,"message_queue"			//name
         ,100                       //max message number
         ,sizeof(int)               //max message size
         );

      unsigned int priority;
      std::size_t recvd_size;

      //Receive 100 numbers
      for(int i = 0; i < 100; ++i){
         int number;
         mq.receive(&number, sizeof(number), recvd_size, priority);
		 printf( "%d\n", number );
         if(number != i || recvd_size != sizeof(number))
		 {
			printf( "receive error\n" );
            return 1;
		 }
      }
   }
   catch(interprocess_exception &ex){
      message_queue::remove("message_queue");
      printf( "%s\n",ex.what() );
      return 1;
   }
   //message_queue::remove("message_queue");
	return 0;
}

int send_msg ()
{
   try{
      //Erase previous message queue
      //message_queue::remove("message_queue");

      //Create a message_queue.
      message_queue mq
         (open_or_create            //open_or_create
         ,"message_queue"           //name
         ,100                       //max message number
         ,sizeof(int)               //max message size
         );

      //Send 100 numbers
      for(int i = 0; i < 100; ++i){
         mq.send(&i, sizeof(i), 0);
      }
   }
   catch(interprocess_exception &ex){
	   printf( "%s\n",ex.what() );
      return 1;
   }

   return 0;
}

int main( int argc, char** argv )
{
	if ( argc < 2 )
		return sysv_msg();
	
	int param = atoi( argv[1] );
	
	switch( param )
	{
	case 0:
		return sysv_msg();
	case 1:
		return send_msg();
	case 2:
		return recv_msg();
	default:
		break;
	}

	return 0;
}